package com.tonicgb.shared.core.crud.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tonicgb.shared.core.crud.entity.Page;
import com.tonicgb.shared.core.crud.dao.CruDao;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.List;
/**
 * @author zhaiyujin
 * @date 2021-09-06 23:50:45
 * @说明 curd 抽象服务类,如果T不集成BaseEntity则无法使用findPage
 */
public abstract class CrudService<D extends CruDao<T>,T> extends ServiceImpl<D,T> {

    public static int  pageNo=1;
    public static int pageSize=10;
    @Autowired
    private D d;

    public T get(T entity){
        return d.get(entity);
    }

    public Page<T> findPage(T entity){
        Page<T> page=new Page<>();
        Class<?> c=entity.getClass().getSuperclass();

        try {
            Field pageNoField=c.getDeclaredField("pageNo");
            Field pageSizeField=c.getDeclaredField("pageSize");
            int o1=(int)pageNoField.get(entity);
            int o2 =(int)pageSizeField.get(entity);
            pageNo= (o1==0)? pageNo: o1;
            pageSize= (o2==0)? pageSize: o2;

        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        PageHelper.startPage(pageNo,pageSize);
        List<T> list=d.findList(entity);
        PageInfo pageInfo = new PageInfo<>(list);
        page.setList(list);
        page.setTotalPage(pageInfo.getPages());
        page.setPage(pageInfo.getPageNum());
        page.setLimit(pageInfo.getPageSize());
        page.setTotal(pageInfo.getTotal());
        return page;
    }

}
